package com.qsmx.store.app.main.login;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.R2;
import com.qsmx.store.app.entity.login.LoginEntity;
import com.qsmx.store.app.entity.login.MachineEntity;
import com.qsmx.store.app.fustion.FustionManager;
import com.qsmx.store.app.http.HttpHelper;
import com.qsmx.store.app.http.HttpUrl;
import com.qsmx.store.app.main.AppHomeDelegate;
import com.qsmx.store.app.main.display.DefaultDisplay;
import com.qsmx.store.app.util.Base64;
import com.qsmx.store.app.util.DisplayUtil;
import com.qsmx.store.app.util.RSAUtils;
import com.qsmx.store.app.util.StringUtil;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;
import com.qsmx.store.core.util.loader.AtmosLoader;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class LoginDelegate extends AtmosDelegate {
    private DefaultDisplay display;
    private ArrayAdapter userArrayAdapter;
    private ArrayAdapter shiftArrayAdapter;
    private List<String> mUserList = new ArrayList<>();
    private List<String> mShiftList = new ArrayList<>();
    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
    public static String KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK4E//dlqweaTKEnlcgwEYl3YiLei/0e2eRjgFlNjWjFYXhmKf0ILZsFp6CCbTWrFDuw19/YzODdWrCLZm3fLXkCAwEAAQ==";

    private String mUserAccount;
    private String mShiftCode;

    @BindView(R2.id.sp_account)
    AppCompatSpinner spAccount = null;
    @BindView(R2.id.sp_shift)
    AppCompatSpinner spShift = null;
    @BindView(R2.id.tv_business_date)
    AppCompatTextView tvBusinessDate;
    @BindView(R2.id.et_password)
    AppCompatEditText etPassword;

    @OnClick(R2.id.tv_read_card)
    void onReadCard() {
        // TODO: 2022-01-26 调用读卡器读卡
    }

    @OnClick(R2.id.tv_login)
    void onLogin() {
        if (StringUtil.isNotEmpty(etPassword.getText().toString())) {
            login(mUserAccount, etPassword.getText().toString(), "", "", "0", "1");
        } else {
            showLongToast("请输入密码");
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_login;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        requestAlertWindowPermission();
        initData();
        initView();
    }

    private void initData() {
        for (MachineEntity.UserListBean data : FustionManager.mMachineData.getUserList()) {
            mUserList.add(data.getUsername());
        }

        for (MachineEntity.ShiftListBean data : FustionManager.mMachineData.getShiftList()) {
            mShiftList.add(data.getShiftCode());
        }
    }

    private void initView() {
        tvBusinessDate.setText(FustionManager.mMachineData.getBusinessDate());
        userArrayAdapter = new ArrayAdapter(getContext(), R.layout.item_spinner_select, mUserList);
        userArrayAdapter.setDropDownViewResource(R.layout.item_spinner_drop);
        spAccount.setAdapter(userArrayAdapter);

        spAccount.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mUserAccount = FustionManager.mMachineData.getUserList().get(position).getUsername();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        shiftArrayAdapter = new ArrayAdapter(getContext(), R.layout.item_spinner_select, mShiftList);
        shiftArrayAdapter.setDropDownViewResource(R.layout.item_spinner_drop);
        spShift.setAdapter(shiftArrayAdapter);

        if (FustionManager.mMachineData.getShiftList().get(0).getShiftStatus() == 0) {
            spShift.setSelection(0);
        } else {
            spShift.setSelection(1);
        }

        spShift.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mShiftCode = String.valueOf(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    /**
     * @param userName 用户名
     * @param password 密码
     * @param code     校验码
     * @param uuid     UUID码
     * @param type     登录类型 0-吧台 1-后管
     * @param shift    班次
     */
    private void login(String userName, String password, String code, String uuid, String type, String shift) {
        JSONObject object = new JSONObject();
        object.put("username", userName);
        try {
            object.put("password", Base64.encode(RSAUtils.encryptByPublicKey(KEY, password)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        object.put("code", code);
        object.put("uuid", uuid);
        object.put("type", type);
        object.put("shift", shift);

        HttpHelper.RestClientPostRaw(object, HttpUrl.LOGIN, new ISuccess() {
            @Override
            public void onSuccess(int code, String response) {

                Type type = new TypeToken<LoginEntity>() {
                }.getType();
                Gson gson = new Gson();
                LoginEntity mData = gson.fromJson(response, type);

                FustionManager.mLoginData = mData;

                getSupportDelegate().start(new AppHomeDelegate());
            }
        }, new IError() {
            @Override
            public void onError(int code, String msg) {
                showLongToast(msg);
            }
        }, new IFailure() {
            @Override
            public void onFailure() {

            }
        });
    }


    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startCheckFile() {
        display = (DefaultDisplay) DisplayUtil.showDefaultDisplay(getContext());
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileRational(PermissionRequest request) {
        showRationalDialog(R.string.get_press, request);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    public void requestAlertWindowPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(getProxyActivity())) {
                Toast.makeText(getContext(), "请授予副屏幕使用权限！", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getProxyActivity().getPackageName()));
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
            } else {
                // Already hold the SYSTEM_ALERT_WINDOW permission, do addview or something.
                LoginDelegatePermissionsDispatcher.startCheckFileWithCheck(this);
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (!Settings.canDrawOverlays(getContext())) {
                // SYSTEM_ALERT_WINDOW permission not granted...
                Toast.makeText(getContext(), "副屏幕使用权限获取失败！", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "副屏幕使用权限获取成功！", Toast.LENGTH_SHORT).show();
                // Already hold the SYSTEM_ALERT_WINDOW permission, do addview or something.
                LoginDelegatePermissionsDispatcher.startCheckFileWithCheck(this);
            }
        }
    }

}
